package wxjsapi

import (
	"context"
	"github.com/gin-gonic/gin"
	"github.com/wechatpay-apiv3/wechatpay-go/core"
	"github.com/wechatpay-apiv3/wechatpay-go/core/auth/verifiers"
	"github.com/wechatpay-apiv3/wechatpay-go/core/downloader"
	"github.com/wechatpay-apiv3/wechatpay-go/core/notify"
	"github.com/wechatpay-apiv3/wechatpay-go/services/payments"
	"github.com/wechatpay-apiv3/wechatpay-go/services/payments/jsapi"
	"github.com/wechatpay-apiv3/wechatpay-go/utils"
	"math"
)

// JsApiPay 微信jsApi支付
// @param openid string
// @param goodsName string 商品名称
// @param orderNo string 支付单号
// @param Total float64 支付金额
func JsApiPay(openid, goodsName, orderNo string, Total float64) (map[string]any, error) {
	Total = math.Ceil(Total * 100.00)
	client, ctx, err := InitClient()
	if err != nil {
		return nil, err
	}
	svc := jsapi.JsapiApiService{Client: client}
	// 得到prepay_id，以及调起支付所需的参数和签名
	resp, _, err := svc.PrepayWithRequestPayment(ctx,
		jsapi.PrepayRequest{
			Appid:       core.String(Appid),
			Mchid:       core.String(mchID),
			Description: core.String(goodsName),
			OutTradeNo:  core.String(orderNo),
			Attach:      core.String(""),
			NotifyUrl:   core.String("https://runnong.csjwlkj.cn/order/notice"),
			//NotifyUrl: core.String("http://rproxy.csjwlkj.cn/order/notice"),
			Amount: &jsapi.Amount{
				Total: core.Int64(int64(Total)),
			},

			Payer: &jsapi.Payer{
				Openid: core.String(openid),
			},
			SettleInfo: &jsapi.SettleInfo{
				ProfitSharing: core.Bool(false),
			},
		},
	)
	if err != nil {
		return nil, err
	}
	data := make(map[string]any)
	data["Appid"] = resp.Appid
	data["NonceStr"] = resp.NonceStr
	data["Package"] = resp.Package
	data["PrepayId"] = resp.PrepayId
	data["TimeStamp"] = resp.TimeStamp
	data["sign"] = resp.PaySign
	return data, err

}

// Notice 回调
func Notice(c *gin.Context) (*notify.Request, *payments.Transaction, error) {
	mchPrivateKey, err := utils.LoadPrivateKeyWithPath("conf/apiclient_key.pem")

	if err != nil {
		return nil, nil, err
	}

	ctx := context.Background()
	// 1. 使用 `RegisterDownloaderWithPrivateKey` 注册下载器
	err = downloader.MgrInstance().RegisterDownloaderWithPrivateKey(ctx, mchPrivateKey, mchCertificateSerialNumber, mchID, mchAPIv3Key)
	// 2. 获取商户号对应的微信支付平台证书访问器
	certificateVisitor := downloader.MgrInstance().GetCertificateVisitor(mchID)
	// 3. 使用证书访问器初始化 `notify.Handler`
	handler := notify.NewNotifyHandler(mchAPIv3Key, verifiers.NewSHA256WithRSAVerifier(certificateVisitor))
	transaction := new(payments.Transaction)
	notifyReq, err := handler.ParseNotifyRequest(context.Background(), c.Request, transaction)
	// 如果验签未通过，或者解密失败
	if err != nil {
		return nil, nil, err
	}
	return notifyReq, transaction, err

}
